<?php

namespace Addons\BLConn\Controller;

use Home\Controller\AddonsController;

class WebController extends AddonsController {

    public function index() {
        $token = get_token();
        $openId = get_openid();
        $token == -1 && $this->error('获取微信Token错误');
        $openId == -1 && $this->error('获取用户OpenId错误');

        $userModel = M('user');
        $score_log_mdl = M('score_log');
        $myInfo = $userModel->where("token='$token' and openId='$openId'")->find();
        //$myInfo || $this->error('您尚未注册');
        $myInfo || redirect(U('register'));

        $myReferrer = $userModel->where('id='.$myInfo['referrerId'])->find();
        $referers = $userModel->where('referrerId='.$myInfo['id'])->order('id desc')->limit(3)->select();
        $referers_amount = $userModel->where('referrerId='.$myInfo['id'])->count();
        $scoreLogs = $score_log_mdl->where('uid='.$myInfo['id'])->order('id desc')->limit(10)->select();
        $this->assign('myinfo', $myInfo);
        $this->assign('myReferrer', $myReferrer);
        $this->assign('referers', $referers);
        $this->assign('referers_amount', $referers_amount);
        $this->assign('scoreLogs', $scoreLogs);

        //推荐二维码
        $key = 'referUrl'.$myInfo['id'];
        if(!cookie($key)) {
            $qrCodeUrl = D('Home/QrCode')->QrcodeCreate($myInfo['id']);
            $qrCodeUrl && cookie($key, $qrCodeUrl, 604800);
        }
        $this->assign('referUrl', cookie($key));

        $this->display();
    }

    //ajax 上拉获取更多数据
    public function get_more_logs() {
        $page_size = 10;
        $page_num = I('page_num', 1);
        $user_id = I('uid', 0);
        $score_log_mdl = M('score_log');
        $scoreLogs = $score_log_mdl->where('uid='.$user_id)->order('id desc')->limit($page_size * $page_num)->select();
        foreach($scoreLogs as &$scorelog) {
            $scorelog['createTime'] = time_format($scorelog['createTime']);
        }
        $return['scoreLogs'] = $scoreLogs;
        $this->ajaxReturn($return);

    }

    //注册页面
    public function register() {
        $userModel = M('user');
        $token = get_token();
        $openId = get_openid();
        $token == -1 && $this->error('获取微信Token失败');
        $openId == -1 && $this->error('获取用户OpenId失败');

        //判断用户是否已注册
        $isRegister = $userModel->where("token='$token' and openId='$openId'")->count();
        $isRegister && redirect(U('index'));

        //获取微信用户信息
        $subscribeUrl = 'http://mp.weixin.qq.com/s?__biz=MzIwNTA2NDM5Mw==&mid=209573109&idx=1&sn=38484e0783dd2497edab406dc85274e0#rd';
        $wxUserInfo = getWeixinUserInfo($openId, $token);
        $wxUserInfo['subscribe'] || $this->error('请先关注公众号', $subscribeUrl);

        //推荐人ID
        $referrerId = I("referrer_id");

        $data['nickname'] = $wxUserInfo['nickname'];
        $data['image'] = $wxUserInfo['headimgurl'];
        $data['sex'] = $wxUserInfo['sex'];
        $data['referrerId'] = $referrerId;
        $data['score'] = 0;
        $data['integralTank'] = 0;
        $data['registerTime'] = time();
        $data['openId'] = $openId;
        $data['token'] = $token;
        checkUserId();
        $result = $userModel->add($data);
        if($result) {
            $config = getAddonConfig('BLCConfig');
            if(!empty($config['referrerScore']) && !empty($referrerId)) {
                $userModel->where("id=$referrerId")->setInc('integralTank', $config['referrerScore']);
                //判断会员是否已经达到积分罐上限
                checkIntegralTank($referrerId);
            }
            //$this->success('注册成功', U('index'));
            redirect(U('index'));

        } else {
            $this->error('注册失败');
        }
    }

    //检查用户ID
    public function checkUserId(){
        $Model = M();
        $res = $Model->query('select AUTO_INCREMENT from INFORMATION_SCHEMA.TABLES where TABLE_NAME="__PREFIX__user"');
        $next_id = $this_id = $res[0]['AUTO_INCREMENT'];
        $pos = strpos($next_id,'444');
        if($next_id<100){
            $next_id += 100;
        }
        if($pos !== false){
            $len = strlen($next_id);
            $next_id += pow(10,$len-($pos+3));
        }
        if($this_id != $next_id){
            $Model->execute('alter table __PREFIX__user AUTO_INCREMENT='.$next_id);
        }
    }

    //检查会员是否有未确认订单
    public function checkNewOrder() {
        $return['status'] = 0;
        $uid = I('uid');
        $uid || $this->ajaxReturn($return);

        $orderData = M('order')->where("uid=$uid and status=0")->order('createTime desc')->find();
        $orderData || $this->ajaxReturn($return);   //查无未确认订单

        $return['status'] = 1;
        $return['oid'] = $orderData['id'];
        $return['detail'] = $orderData['detail'];
        $this->ajaxReturn($return);
    }

    //会员处理订单
    public function handleOrder() {
        $return['status'] = 0;
        $uid = I('uid');
        $oid = I('oid');
        $isConfirm = I('is_confirm', 0);
        ($uid && $oid) || $this->ajaxReturn($return);

        $orderModel = M('order');
        $userModel = M('user');
        $orderData = $orderModel->where("id=$oid and uid=$uid and status=0")->find();
        $orderData || $this->ajaxReturn($return);

        if($isConfirm) { //确认扣分
            $changeOrderStatus = $orderModel->where("id=$oid")->setField('status', 1);  //已确认
            if($changeOrderStatus) {
                //扣除会员积分
                $changeUserScore = $userModel->where("id=$uid")->setDec('score', $orderData['score']);
                if($changeUserScore) {
                    //调整爱心积分罐
                    M('Config')->where("name='LOVE_INTEGRAL_TANK'")->setInc('value', $orderData['score']);

                    //积分记录
                    $userLog = array(
                        'uid' => $uid,
                        'score' => $orderData['score'],
                        'type' => 2,    //支出
                        'detail' => $orderData['detail'],
                        'adminId' => $orderData['adminId'],
                        'createTime' => time()
                    );
                    M('score_log')->add($userLog);

                    $return['status'] = 1;
                    $this->ajaxReturn($return);
                } else {
                    $orderModel->where("id=$oid")->setField('status', 0);  //待确认
                    $this->ajaxReturn($return);
                }
            } else {
                $this->ajaxReturn($return);
            }

        } else { //取消扣分
            $changeOrderStatus = $orderModel->where("id=$oid and uid=$uid and status=0")->setField('status', 2);   //已取消

            if($changeOrderStatus) {
                $return['status'] = 1;
                $this->ajaxReturn($return);
            } else {
                $this->ajaxReturn($return);
            }
        }

        $this->ajaxReturn($return);
    }

    //积分兑换
    public function exchange() {
        $openId = get_openid();
        $userModel = M('user');
        $myInfo = $userModel->where("openId='$openId'")->find();
        if(empty($myInfo)) {
            $this->error('获取用户信息出错');
        }

        if(IS_POST) {
            //北京时间0：00-8：00不触发红包赠送
            $currentHour = date('G');
            if(0 <= $currentHour && $currentHour < 8) {
                $this->error('0：00-8：00时段不可进行兑换');
            }

            //检查数据
            $money = I('money');
            $needScore = $money * 100;
            if(!in_array($money, array(10, 50, 100, 200)) || !(1 <= $money && $money <= 200)) {     //加入红包金额限制
                $this->error('非法参数');
            } elseif($myInfo['score'] < $needScore) {
                $this->error('您的积分不足');
            }


            M()->startTrans();  //启动事务
            //扣除用户积分
            $userData = array(
                'score' => array('exp', "score-{$needScore}"),
                'redPackAmount' => array('exp', "redPackAmount+{$money}")
            );
            $changeUserScore = $userModel->where("openId='$openId'")->save($userData);

            //积分记录
            $userLog = array(
                'uid' => $myInfo['id'],
                'score' => $needScore,
                'type' => 2,    //支出
                'detail' => "积分兑换红包{$money}元",
                'createTime' => time()
            );
            $createUserLog = M('score_log')->add($userLog);


            //调用红包接口
            if($changeUserScore && $createUserLog) {
                require_once(SITE_PATH.'/WxpayAPI/lib/WxPay.Api.php');
                $mchBillNo = \WxPayConfig::MCHID.date("Ymd").substr(uniqid(), -10);

                $input = new \WxPaySendRedPack();
                $input->SetSend_name('纤仙缘');
                $input->SetMch_billno($mchBillNo);
                $input->SetRe_openid($openId);
                $input->SetTotal_amount($money * 100);
                $input->SetWishing('感谢您参加积分兑换活动，祝您生活愉快！');
                $input->SetAct_name('积分兑换活动');
                $input->SetRemark('积分越多得越多，快来抢！');
                $result = \WxPayApi::sendRedPack($input);

                if($result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS") {   //发放成功
                    M()->commit();  //提交事务
                    $this->success('恭喜您积分兑换成功');
                }
            }

            M()->rollback();  //事务回滚
            $this->error('积分兑换失败，请稍后再试');

        } else {
            $this->assign('myInfo', $myInfo);
            $this->display();
        }
    }
}
